package com.ynet.middleground.oss.oauth.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.oss.dao.OauthUserAuthenticationMapper;
import com.ynet.middleground.oss.dao.OauthUserRoleMapper;
import com.ynet.middleground.oss.entity.OauthUserAuthentication;
import com.ynet.middleground.oss.oauth.service.OauthUserAuthenticationService;

/**
 * <p>
 * oauth认证用户表 服务实现类
 * </p>
 *
 * @author Suremotoo
 * @since 2019-05-09
 */
@Service
public class OauthUserAuthenticationServiceImpl extends
    ServiceImpl<OauthUserAuthenticationMapper, OauthUserAuthentication> implements OauthUserAuthenticationService {

    /**
     * 角色权限 前缀
     *
     * @see org.springframework.security.access.vote.RoleVoter
     */
    protected static final String ROLE_PREFIX = "ROLE_";

    @Autowired
    OauthUserRoleMapper oauthUserRoleMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        OauthUserAuthentication user = this.getOne(
            new LambdaQueryWrapper<OauthUserAuthentication>().eq(OauthUserAuthentication::getUsername, userName));
        if (user == null) {
            throw new BusinessException("用户名或密码无效", "");
        }
        user.setAuthorities(getAuthority(user.getId()));
        IfpLogger.debug("UserDetails user info: {}", user.toString());
        return user;
        // return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
        // getAuthority());
    }

    /**
     * 查询用户对应角色权限列表
     *
     * @param userId 用户 ID
     * @return 用户角色名称列表
     */
    private List<SimpleGrantedAuthority> getAuthority(Integer userId) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<Map<String, Object>> oauthUserRoles = oauthUserRoleMapper.listRolesByUserId(userId);
        if (oauthUserRoles != null) {
            for (Map<String, Object> role : oauthUserRoles) {
                authorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + role.get("role_name")));
            }
        }
        return authorities;
    }

}
